<template>
  <el-drawer v-model="visible" :title="getDrawerTitle" direction="rtl" size="500px" :before-close="handleClose">
    <div class="drawer-content">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="top">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入权限名称" />
        </el-form-item>

        <el-form-item label="权限代码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入权限代码（如：user:view）" :disabled="isEdit" />
          <div class="form-tip">权限代码用于系统内部标识，创建后不可修改</div>
        </el-form-item>

        <el-form-item label="权限类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="模块" value="模块" />
            <el-option label="操作" value="操作" />
            <el-option label="页面" value="页面" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="parentData.id" label="父级权限">
          <el-input :value="`${parentData.name} (${parentData.code})`" disabled />
        </el-form-item>

        <el-form-item label="权限描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入权限描述" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" placeholder="排序值" style="width: 100%" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="启用">启用</el-radio>
            <el-radio value="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  permissionData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  parentData: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const defaultFormData = {
  id: null,
  name: '',
  code: '',
  type: '操作',
  description: '',
  sort: 0,
  status: '启用',
  remark: '',
  parentId: null
}

const formData = reactive({ ...defaultFormData })

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_:]*$/, message: '权限代码只能包含字母、数字、下划线和冒号，且以字母开头', trigger: 'blur' },
    { min: 2, max: 100, message: '权限代码长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入权限描述', trigger: 'blur' },
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

const getDrawerTitle = computed(() => {
  if (props.isEdit) {
    return '编辑权限'
  } else if (props.parentData.id) {
    return `添加子权限 - ${props.parentData.name}`
  } else {
    return '添加权限'
  }
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (props.isEdit && props.permissionData) {
      // 编辑模式，填充数据
      Object.assign(formData, {
        ...defaultFormData,
        ...props.permissionData
      })
    } else {
      // 新增模式，重置表单
      Object.assign(formData, {
        ...defaultFormData,
        parentId: props.parentData.id || null,
        type: props.parentData.id ? '操作' : '模块' // 如果有父级，默认为操作类型
      })
    }

    // 重置表单验证
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
})

// 方法
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    submitting.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    emit('submit', { ...formData })

    ElMessage.success(props.isEdit ? '更新成功' : '添加成功')
    handleClose()

  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped lang="scss">
.drawer-content {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px 20px 16px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-drawer__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-radio-group) {
  .el-radio {
    margin-right: 24px;
  }
}
</style>
